package services

import (
	"errors"
	"go-mvc-ecommerce/models"

	"gorm.io/gorm"
)

type UserService struct {
	db *gorm.DB
}

func NewUserService(db *gorm.DB) *UserService {
	return &UserService{db: db}
}

// 创建用户
func (s *UserService) CreateUser(username, password string) (*models.User, error) {
	user := &models.User{
		Username: username,
		Password: password, // 注意：实际项目中应该加密存储
		Balance:  0,
	}

	result := s.db.Create(user)
	if result.Error != nil {
		return nil, result.Error
	}

	return user, nil
}

// 更新密码
func (s *UserService) UpdatePassword(userID uint, newPassword string) error {
	result := s.db.Model(&models.User{}).Where("id = ?", userID).Update("password", newPassword)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("没有找到用户")
	}
	return nil
}

// 获取用户
func (s *UserService) GetUserByID(userID uint) (*models.User, error) {
	var user models.User
	result := s.db.First(&user, userID)
	if result.Error != nil {
		return nil, result.Error
	}
	return &user, nil
}

// 获取用户
func (s *UserService) GetUserByUsername(username string) (*models.User, error) {
	var user models.User
	result := s.db.Where("username = ?", username).First(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	return &user, nil
}

// 增加余额
func (s *UserService) AddBalance(userID uint, balance float64) error {
	result := s.db.Model(&models.User{}).Where("id = ?", userID).Update("balance", balance)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("没有找到用户")
	}
	return nil
}
